﻿using System;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace HenhouseEnvironmentCtrl
{
    public partial class RegisterForm : Form
    {
        public RegisterForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 注册按钮点击事件
        /// </summary>
        private void BtnRegister_Click(object sender, EventArgs e)
        {
            // 检查必填项是否为空
            if (string.IsNullOrEmpty(txtUsername.Text) || string.IsNullOrEmpty(txtPassword.Text) || string.IsNullOrEmpty(txtConfirmPassword.Text) || string.IsNullOrEmpty(txtCDK.Text))
            {
                MessageBox.Show("用户名、密码、确认密码和CDK不能为空");
                return;
            }

            // 检查用户名长度
            if ( txtUsername.Text.Length > 20)
            {
                MessageBox.Show("用户名长度应大于20个字符");
                return;
            }

            // 检查密码长度
            if (txtPassword.Text.Length < 8 || txtPassword.Text.Length > 20)
            {
                MessageBox.Show("密码长度应在8到20个字符之间");
                return;
            }

            // 检查密码和确认密码是否一致
            if (txtPassword.Text != txtConfirmPassword.Text)
            {
                MessageBox.Show("密码和确认密码不一致");
                return;
            }

            // 验证CDK并注册用户
            if (ValidateCDK(txtCDK.Text))
            {
                if (RegisterUser(txtUsername.Text, txtPassword.Text))
                {
                    MessageBox.Show("注册成功");
                    DecreaseCDKUsage(txtCDK.Text);
                    this.Close();
                }
                else
                {
                    MessageBox.Show("注册失败");
                }
            }
            else
            {
                MessageBox.Show("CDK 无效或已达到使用次数上限");
            }
        }

        /// <summary>
        /// 注册用户
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns>是否注册成功</returns>
        private bool RegisterUser(string username, string password)
        {
            try
            {
                using (SqlConnection sqlConnection = DBConnection.CreateConnection())
                {
                    sqlConnection.Open();
                    using (SqlCommand cmd = sqlConnection.CreateCommand())
                    {
                        cmd.CommandText = "INSERT INTO Users (AdminName, Password, UserRole) VALUES (@username, @password, 'User')";

                        cmd.Parameters.AddWithValue("@username", username);
                        cmd.Parameters.AddWithValue("@password", password); // 不加密密码，直接存储明文
                        cmd.ExecuteNonQuery();
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("注册失败: " + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 验证CDK
        /// </summary>
        /// <param name="cdk">CDK</param>
        /// <returns>CDK是否有效</returns>
        private bool ValidateCDK(string cdk)
        {
            try
            {
                using (SqlConnection sqlConnection = DBConnection.CreateConnection())
                {
                    sqlConnection.Open();
                    using (SqlCommand cmd = sqlConnection.CreateCommand())
                    {
                        cmd.CommandText = "SELECT IsAvailable, AvailableUses FROM CDK WHERE CDK = @cdk";
                        cmd.Parameters.AddWithValue("@cdk", cdk);
                        SqlDataReader reader = cmd.ExecuteReader();
                        if (reader.Read())
                        {
                            bool isAvailable = Convert.ToBoolean(reader["IsAvailable"]);
                            int availableUses = Convert.ToInt32(reader["AvailableUses"]);
                            return isAvailable && availableUses > 0;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("验证CDK失败: " + ex.Message);
            }
            return false;
        }

        /// <summary>
        /// 减少CDK使用次数
        /// </summary>
        /// <param name="cdk">CDK</param>
        private void DecreaseCDKUsage(string cdk)
        {
            try
            {
                using (SqlConnection sqlConnection = DBConnection.CreateConnection())
                {
                    sqlConnection.Open();
                    using (SqlCommand cmd = sqlConnection.CreateCommand())
                    {
                        cmd.CommandText = "UPDATE CDK SET AvailableUses = AvailableUses - 1 WHERE CDK = @cdk";
                        cmd.Parameters.AddWithValue("@cdk", cdk);
                        cmd.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("减少CDK使用次数失败: " + ex.Message);
            }
        }

        /// <summary>
        /// 关闭按钮点击事件
        /// </summary>
        private void BtnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
